<script setup lang="ts">
//加载时获取分类
import { computed, onBeforeMount, onMounted, reactive, ref, watch } from 'vue'
import { getCategoryTree } from '@/api/category'
import { useProductStore } from '@/stores/modudels/product2'
import { getAttrListByCategoryId } from '@/api/attr'
import CunstomerUpload from '@/components/upload/CunstomerUpload.vue'
import TEditor from '@/components/tinymce/TEditor.vue'
import { findSpuById, saveSpu, updateSpu } from '@/api/product'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const $router = useRouter()
//商品仓库
const productStore = useProductStore()
let formData = productStore.formData
//商品分类
const categoryTree = ref([])

//收集form数据, 在新增和编辑的时候对应不同的逻辑
const interimFormData = ref({
  categoryId: null,
  title: '',
  subTitle: '',
  description: '',
  credits: 0,
  checkedValues: [],
  isPreview: false,
  isRecommend: false,
  isNew: false,
  skuInfoList: [],
  spuContent: ''
})

//属性值
const allAttrValues = ref([])
//商品详情
const spuDetailRef = ref(null)
//设置商品详情, 编辑的时候使用
const setContent = (event) => {
  spuDetailRef.value.handleSetContent(interimFormData.value.spuContent)
  // spuDetailRef.value.handleSetContent('123123123123')
  event.preventDefault()
}
//onMounted
onMounted(async () => {
  console.log('productStore.formData:',productStore.formData)
  //编辑
  if (route.query.id) {
    interimFormData.value = formData
    skuAttrTableData.value = formData.skuInfoList
    console.log('mounted skuAttrTableData', skuAttrTableData.value)
    console.log('mounted formData', formData)
    console.log('mounted interimFormData', interimFormData.value.skuInfoList)
  }
  //新增
  const result = await getCategoryTree()
  if (result.code == 200) {
    categoryTree.value = result.data
  }
  if (interimFormData.value.categoryId) {
    const result = await getAttrListByCategoryId(formData.categoryId)
    if (result.code == 200) {
      for (let datum of result.data) {
        allAttrValues.value.push(datum)
        if (datum.attrValueDTOList.length > 0) {
          allAttrValues.value.push(...datum.attrValueDTOList)
        }
      }
      console.log('allAttrValues', allAttrValues.value)
    }
  }
  //设置属性值的选中状态
  if (interimFormData.value.skuInfoList) {
    let attrValuesList = []
    interimFormData.value.skuInfoList.forEach(item => {
      attrValuesList.push(...item.attrValueIds)
    })
    console.log('attrValuesList', [...new Set(attrValuesList)])
    checkedValues.value = [...new Set(attrValuesList)]
  }
})

// 级联选择器属性设置
const props = ref(
  {
    value: 'id',
    label: 'name',
    children: 'child'
  }
)

//选择分类方法
const handleCategoryChange = async (value) => {
  console.log('handleCategoryChange', value)
  interimFormData.value.categoryId = value[value.length - 1]
  const result = await getAttrListByCategoryId(interimFormData.value.categoryId)
  if (result.code == 200) {
    for (let datum of result.data) {
      allAttrValues.value.push(datum)
      if (datum.attrValueDTOList.length > 0) {
        allAttrValues.value.push(...datum.attrValueDTOList)
      }
    }
    console.log('allAttrValues', allAttrValues.value)
  }
}


//选择商品属性值
const checkedValues = ref([])
const valuesChange = (value) => {
  checkedValues.value = value
}

// sku组合表格数据
const skuAttrTableData = ref([])
//根据选择的属性值从所有的属性值中筛选
const filterAttrValue = (value) => {
  let allValuesCombination = []
  value.forEach(item => {
    allAttrValues.value.filter(attr => {
      if (attr.id === item) {
        allValuesCombination.push(attr)
      }
    })
  })
  return allValuesCombination
}
//根据attrId进行分组
const groupAttrValue = (value) => {
  return value.reduce((groups, item) => {
    const key = item.attrId
    if (!groups[key]) {
      groups[key] = []
    }
    groups[key].push(item)
    return groups
  }, []).filter(item => item.length > 0)
}
//监视选择的属性值
watch(checkedValues, async (newValaue, oldValue) => {
  if (!route.query.id) {
    skuAttrTableData.value = []
    //根据选择的属性值从所有的属性值中筛选
    let allValuesCombination = filterAttrValue(checkedValues.value)
    //将allValuesCombination根据attrId进行分组
    const groups = groupAttrValue(allValuesCombination)
    console.log('groups:', groups)
    // //将groups中的数据进行笛卡尔积
    let result = cartesian(groups)
    console.log('result:', result)
    if (result && result.length > 0) {
      result.forEach(item => {
        if (item.length > 0) {
          let str = ''
          let ids = []
          item.forEach(val => {
            str += val.name + '  '
            ids.push(val.id)
          })
          skuAttrTableData.value.push({
            attrValueName: str,
            attrValueIds: ids
          })
        } else {
          let attrName = allAttrValues.value.filter(t => t.id === item.attrId)[0].name
          skuAttrTableData.value.push({
            attrValueName: attrName + ':' + item.name,
            attrValueIds: item.id
          })
        }
      })
    }
  } else {
    if (formData.skuInfoList.length < 1) {
      //根据选择的属性值从所有的属性值中筛选
      let allValuesCombination = filterAttrValue(checkedValues.value)
      //将allValuesCombination根据attrId进行分组
      const groups = groupAttrValue(allValuesCombination)
      console.log('groups:', groups)
      // //将groups中的数据进行笛卡尔积
      let result = cartesian(groups)
      console.log('result:', result)
      if (result && result.length > 0) {
        result.forEach(item => {
          if (item.length > 0) {
            let str = ''
            let ids = []
            item.forEach(val => {
              str += val.name + '  '
              ids.push(val.id)
            })
            skuAttrTableData.value.push({
              attrValueName: str,
              attrValueIds: ids
            })
          } else {
            let attrName = allAttrValues.value.filter(t => t.id === item.attrId)[0].name
            skuAttrTableData.value.push({
              attrValueName: attrName + ':' + item.name,
              attrValueIds: item.id
            })
          }
        })
      }
    } else {
      console.log('newValaue', newValaue)
      console.log('oldValue', oldValue)
      //oldValue与newValue取差集
      let difference = oldValue.filter(item => !newValaue.includes(item))
      console.log('difference', difference)
      //从 skuAttrTableData 中根据difference的变化删除对应的attrValueId的数据
      skuAttrTableData.value = skuAttrTableData.value.filter(item => {
        if (Array.isArray(item.attrValueIds)) {
          return !item.attrValueIds.includes(difference[0])
        } else {
          //新增一个数据
          return true
        }
      })

    }
    console.log('skuAttrTableData editttttt:', skuAttrTableData.value)


  }

})
//监视skuAttrTableData
// watch(skuAttrTableData, () => {
//   interimFormData.value.skuInfoList = skuAttrTableData
// }, {
//   deep: true
// })

//笛卡尔积
function cartesian(arr) {
  if (arr.length === 0) return
  return arr.reduce(
    (a, b) =>
      a.flatMap(d => b.map(e => [d, e].flat()))
  )
}


const handleSubmit = async () => {
  interimFormData.value.spuContent = spuDetailRef.value.handleGetContent()
  interimFormData.value.checkedValues = checkedValues.value
  interimFormData.value.skuInfoList = skuAttrTableData.value
  let result
  if (formData.id) {
    //更新
    console.log('interimFormData:', interimFormData.value)
    result = await updateSpu(interimFormData.value)
  } else {
    result = await saveSpu(interimFormData.value)
  }
  if (result.code == 200) {
    $router.push('/product/spu')
    interimFormData.value = ref({
      categoryId: null,
      title: '',
      subTitle: '',
      description: '',
      checkedValues: [],
      credits: 0,
      isPreview: false,
      isRecommend: false,
      isNew: false,
      skuInfoList: [],
      spuContent: ''
    })
  }
}

</script>

<template>
  <div class="add_spu_layout">
    <el-form :model="interimFormData" label-width="auto" label-position="left">
      <el-form-item>
        <span>商品基本信息</span>
      </el-form-item>
      <!--      选择分类-->
      <el-form-item label="商品分类">
        <el-cascader
          v-model="interimFormData.categoryId"
          :options="categoryTree"
          :props="props"
          @change="handleCategoryChange"
        />
      </el-form-item>
      <!--商品标题-->
      <el-form-item label="商品标题">
        <el-input v-model="interimFormData.title" placeholder="请输入商品标题" />
      </el-form-item>
      <!--      商品副标题-->
      <el-form-item label="商品副标题" class="desc_text_area_layout">
        <el-input
          class="text_area_class"
          v-model="interimFormData.subTitle"
          placeholder="请输入商品副标题"
        />
      </el-form-item>
      <!--      商品介绍-->
      <el-form-item label="商品介绍" class="desc_text_area_layout">
        <el-input v-model="interimFormData.description" class="text_area_class" type="textarea"
                  placeholder="请输入商品介绍"></el-input>
      </el-form-item>

      <el-form-item>
        <span>商品促销信息</span>
      </el-form-item>
      <el-form-item label="赠送积分">
        <el-input v-model="interimFormData.credits"></el-input>
      </el-form-item>
      <el-form-item label="预告商品">
        <el-switch v-model="interimFormData.isPreview"></el-switch>
      </el-form-item>
      <el-form-item label="商品推荐">
        <el-switch inline-prompt active-text="推荐" inactive-text="不设置为推荐"
                   v-model="interimFormData.isRecommend"></el-switch>
        <el-switch inline-prompt active-text="新品" inactive-text="不设置为新品" v-model="formData.isNew"></el-switch>
      </el-form-item>
      <el-form-item v-if="allAttrValues.length>0">
        <span>商品属性</span>
        <!--        选择规格属性-->
        <el-card>
          <div v-for="(item) in allAttrValues" :key="item">
            <el-checkbox-group @change="valuesChange" v-model="checkedValues">
              <el-checkbox v-for="(value) in item.attrValueDTOList"
                           :label="value.name"
                           :value="value.id"
                           :key="value" />
            </el-checkbox-group>
          </div>
        </el-card>
      </el-form-item>

      <el-form-item>
        <el-table :data="skuAttrTableData" fit border>
          <el-table-column label="sku组合" prop="attrValueName" width="100px" />
          <el-table-column label="销售价格" width="100px">
            <template #default="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="促销价格" width="100px">
            <template #default="scope">
              <el-input v-model="scope.row.countPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="库存" width="80px">
            <template #default="scope">
              <el-input v-model="scope.row.cukun"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="库存预警值" width="100px">
            <template #default="scope">
              <el-input v-model="scope.row.yujing"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="sku编号" width="180px">
            <template #default="scope">
              <el-input v-model="scope.row.skuNum"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="sku主图" width="auto">
            <template #default="scope">
              <CunstomerUpload :index="scope.$index" :imgUrls="scope.row.imgUrl"></CunstomerUpload>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="商品详情">
        <template #default>
          <button @click="setContent">设置详情内容</button>
          <TEditor ref="spuDetailRef"></TEditor>
        </template>
      </el-form-item>

      <!--      提交表单-->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </el-form-item>

    </el-form>
  </div>

</template>

<style scoped lang="scss">

</style>
